package edu.neusoft.yiqibike.common.security;

import edu.neusoft.yiqibike.common.datasource.DynamicDataSourceContextHolder;
import edu.neusoft.yiqibike.common.entity.mysql.Admin;
import edu.neusoft.yiqibike.service.IAdminService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    private IAdminService adminService;

    //权限认证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        DynamicDataSourceContextHolder.setDataSourceType("ds1");
        log.debug("## shiro进行权限识别 ##");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Admin admin = (Admin) principalCollection.getPrimaryPrincipal();
        admin = adminService.getAdminWithRoleAndPermission(admin);
        if (!CollectionUtils.isEmpty(admin.getRoles())) {
            authorizationInfo.addRoles(admin.getRoles());
        }
        if (!CollectionUtils.isEmpty(admin.getPermissions())) {
            authorizationInfo.addStringPermissions(admin.getPermissions());
        }
        log.debug("## 当前登录账号的角色和权限信息：{} ##", admin.toString());
        DynamicDataSourceContextHolder.clearDataSourceType();
        return authorizationInfo;
    }

    //身份验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.debug("## shiro进行身份校验 ##");
        String realname = (String) authenticationToken.getPrincipal();
        Admin admin = adminService.getAdminByRealname(realname);
        if (admin == null) {
            throw new UnknownAccountException("管理员账号不存在，请重新输入!");
        }
        if (admin.getIsEnable() != 1) {
            throw new LockedAccountException("管理员账号已被锁定！");
        }
        //密码加盐
        ByteSource salt = ByteSource.Util.bytes(admin.getSalt());
        return new SimpleAuthenticationInfo(admin, admin.getPassword(), salt, getName());
    }
}
